package com.mynews.activities.collection;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;

import com.mynews.activities.App;
import com.mynews.activities.detail.DetailActivity;
import com.mynews.adapter.CollectionAdp;
import com.mynews.bean.CollectionBean;
import com.mynews.bean.NewsBean;
import com.mynews.databinding.ActivityCollectionBinding;
import com.mynews.utils.BmobApi;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class CollectionVM extends AndroidViewModel {
    @SuppressLint("StaticFieldLeak")
    private static CollectionActivity collectionActivity;
    private final List<CollectionBean> data=new ArrayList<>();
    @SuppressLint("StaticFieldLeak")
    private static ActivityCollectionBinding binding;
    public CollectionVM(@NonNull Application application) {
        super(application);
    }
    public void setBinding(ActivityCollectionBinding binding, CollectionActivity collectionActivity) {
        CollectionVM.binding=binding;
        CollectionVM.collectionActivity=collectionActivity;
        binding.setAdp(new CollectionAdp(collectionActivity, data));
        binding.collectionList.setOnItemClickListener((parent, view, position, id) -> {
            CollectionBean bean = data.get(position);
            BmobApi.get("https://api2.bmob.cn/1/classes/news/" + bean.newsId, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) {
                    try {
                        assert response.body() != null;
                        JSONObject jo = new JSONObject(response.body().string());
                        App.newsBean=new NewsBean(jo.getString("objectId"),jo.getString("title"),jo.getString("content"),jo.getString("ownerId"),jo.getString("updatedAt"),jo.getString("type"),App.user);
                        collectionActivity.startActivity(new Intent(collectionActivity, DetailActivity.class));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

        });
        binding.collectionList.setOnItemLongClickListener((parent, view, position, id) -> {
            AlertDialog.Builder dialog=new AlertDialog.Builder(collectionActivity);
            dialog.setTitle("提示").setMessage("是否移除收藏?").setPositiveButton("移除", (dialog1, which) -> {
                CollectionBean bean = data.get(position);
                BmobApi.delete("https://api2.bmob.cn/1/classes/collection/"+bean.id, new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                        refresh();
                    }
                });
            }).setNeutralButton("取消",null).show();
            return true;
        });
        refresh();
    }
    private void refresh() {
        data.clear();
        BmobApi.get("https://api2.bmob.cn/1/classes/collection?where={\"userId\":\""+ App.user.objectId+"\"}", new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                    for (int i = 0; i < ja.length(); i++){
                        JSONObject jo=ja.getJSONObject(i);
                        data.add(new CollectionBean(jo.getString("objectId"),jo.getString("newsId"),App.user.objectId));
                    }
                    collectionActivity.runOnUiThread(() -> binding.getAdp().notifyDataSetChanged());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
